import axios from 'axios'
export default {
  namespaced: true,
  state: {
    list:[]
  },
  mutations: {
    updateList (state,list) {
       state.list = list
    },
    updateCount(state,{id,count}){
      const item = state.list.find(item => item.goods_id === id)
      if (item) {
        item.goods_count = count
      }
    },
    updateState(state,{id,goods_state}){
      const item = state.list.find(item => item.goods_id === id)
      if (item) {
        item.goods_state = goods_state
        
      }
    },
    updateAllState(state,allState) {
    state.list.forEach(item => item.goods_state = allState);
    }
  },
  actions: {
    async getList(store){
      // 调用接口
     const res =  await axios.get('https://applet-base-api-t.itheima.net/api/cart') 
    //  console.log(res);
     store.commit('updateList',res.data.list)
    }
  },
  getters: {
    isAllChecked(state){
      return state.list.every(item => item.goods_state)
    },
    totalCount(state){
      let count = 0
      state.list.forEach(item =>{
        if (item.goods_state) count += item.goods_state
      })
      return count
    },
    totalPrice(state){
      let price = 0
      state.list.forEach(item =>{
        if (item.goods_state) price += item.goods_price * item.goods_count
      })
      return price
    }

  }
 
}
